<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-form v-loading="loading" inline size="small">
          <el-form-item label="发送模式">
            <el-radio-group v-model="sendData.sendModel" :disabled="connectState.state">
              <el-radio label="ascii">ascii</el-radio>
              <el-radio label="hex">hex</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="接收模式">
            <el-radio-group v-model="connectState.reciveModel" :disabled="connectState.state">
              <el-radio label="ascii">ascii</el-radio>
              <el-radio label="hex">hex</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-input-number v-model="connectState.port" :disabled="connectState.state" placeholder="端口" />
          </el-form-item>
          <el-form-item>
            <el-button v-if="!connectState.state" type="primary" @click="listen">监听</el-button>
            <el-button v-else type="primary" @click="close">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">
        <div class="panel panel-default">
          <div class="panel-heading">客户端列表</div>
          <div class="panel-body" style="height: 400px;overflow-y: scroll">
            <ul class="" style="list-style-type: none;line-height: 1.5;">
              <li v-for="item in clients" :key="item">
                <span class="margin-right"><el-checkbox v-model="item.checked" /></span>
                <b>{{ item.host }}:{{ item.port }}</b>
              </li>
            </ul>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="panel panel-default">
          <div class="panel-heading">输出区</div>
          <div class="panel-body" style="height: 400px;overflow-y: scroll">
            <ul style="line-height: 1.5">
              <li v-for="dataline in dataLines" :key="dataline">
                <span>{{ dataline.time }}</span>
                <span class="margin-left">从 {{ dataline.client.host }}:{{ dataline.client.port }}</span>
                <b v-if="dataline.direction === 'send'" class="text-forestgreen margin-left">发送</b>
                <b v-if="dataline.direction === 'recive'" class="text-danger margin-left">接收</b>
                <span class="margin-left">{{ dataline.message }}</span>
              </li>
            </ul>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import tcp from '@/api/tcp'

let ws = null

window.onbeforeunload = function() {
  if (ws != null) {
    ws.onclose = function() {} // disable onclose handler first
    ws.close()
  }
}

export default {
  name: 'tcpserver',
  data() {
    return {
      loading: false,
      connectState: {
        reciveModel: 'ascii',
        port: 10086,
        state: false,
        reciveData: null
      },
      clients: [],
      sendData: {
        sendModel: 'ascii',
        value: ''
      },
      dataLines: []
    }
  },
  mounted() {
    this.refreshState()
  },
  methods: {
    listen() {
      this.loading = true
      tcp.serverOpen(this.connectState.port, this.connectState.reciveModel).then(res => {
        this.loading = false

        if (res.data.port) {
          this.connectState = res.data
        }
        // 拉取客户端列表
        this.loadClients()

        this.openSocket()
      })
    },
    loadClients() {
      tcp.clients().then(res => {
        this.clients = res.data.map(item => item.hostAndPort)
      })
    },
    openWS() {
      // console.log('打开 websocket')
    },
    closeWS() {
      // console.log('关闭 websocket')
    },
    reviceMessage(event) {
      const data = event.data
      // console.log(data,'收到消息');
      if (data) {
        const jsonData = JSON.parse(data)
        switch (jsonData.type) {
          case 'addclient':
            this.clients.push(jsonData.client)
            break
          case 'delclient':
            for (let i = 0; i < this.clients.length; i++) {
              const client = this.clients[i]
              if (client.host === jsonData.client.host && client.port === jsonData.client.port) {
                this.clients.splice(i, 1)
                break
              }
            }
            break
          case 'data':
            this.dataLines.push({ client: jsonData.client, time: new Date().toLocaleTimeString(), direction: 'recive', message: jsonData.msg })
            break
        }
      }
    },
    openSocket() {
      // 监听后台的消息事件 websocket
      if (typeof (WebSocket) !== 'undefined') {
        const hostAndPort = this.connectState.server.host + ':' + this.connectState.server.port
        ws = new WebSocket('ws://' + hostAndPort + '/server/message')

        ws.onopen = this.openWS
        ws.onclose = this.closeWS
        ws.onmessage = this.reviceMessage
        ws.onerror = function(e) {
          console.log(e)
        }
      }
    },
    refreshState() {
      tcp.serverState(this.connectState.reciveModel).then(res => {
        if (res.data.port) {
          this.connectState = res.data
          if (res.data.state) {
            // 打开 websocket
            this.openSocket()

            // 加载客户端列表
            this.loadClients()
          }
        }
      })
    },
    close() {
      tcp.serverClose().then(res => {
        if (ws) {
          ws.close()
        }
        this.clients = []
        this.refreshState()
      })
    }
  }
}
</script>

<style scoped>
@import "../../assets/custom-theme/bootstrap.css";
.test{}
</style>
